package com.onlineauction.helpers;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;

import com.google.appengine.api.memcache.jsr107cache.GCacheFactory;

public class CacheHandler {

	private static Logger LOGGER = Logger.getLogger(CacheHandler.class
			.getName());

	
	public static Cache getUsernameCache() {
		return getCache(Constants.USERNAME);
	}
	
	
	public static Cache getAuctionBidCache() {
		return getCache(Constants.AUCTION_BID);
	}
	
	
	
	
	/**
	 * This method returns a piece of distributed memory across (potentially)
	 * multiple server instances
	 * 
	 * @return cache which is a memchached (distributed) memory
	 */
	private static Cache getCache(String cacheName) {
		CacheManager cacheManager = CacheManager.getInstance();
		Cache cache = cacheManager.getCache(cacheName);
		if (cache != null) {
			return cache;
		} else {
			LOGGER.info("Create a new cache");
			// set cache expiry time to be 1 hour
			Map cacheMap = new HashMap();
			cacheMap.put(GCacheFactory.EXPIRATION_DELTA, 3600);
			try {
				CacheFactory cacheFactory = cacheManager.getCacheFactory();
				cache = cacheFactory.createCache(cacheMap);
				cacheManager.registerCache(cacheName, cache);
			} catch (Exception e) {
				cache = null;
			}
			return cache;
		}
	}
	

}
